package com.app.adnroid.sichuanxiaoke.cn.xiaokebusiness.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.app.adnroid.sichuanxiaoke.cn.xiaokebusiness.R;
import com.app.adnroid.sichuanxiaoke.cn.xiaokebusiness.Utils.CommonUtil;
import com.app.adnroid.sichuanxiaoke.cn.xiaokebusiness.Utils.Constant;
import com.app.adnroid.sichuanxiaoke.cn.xiaokebusiness.Utils.LogUtil;
import com.app.adnroid.sichuanxiaoke.cn.xiaokebusiness.Utils.MapUtil;
import com.app.adnroid.sichuanxiaoke.cn.xiaokebusiness.Utils.MapUtils;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiCitySearchOption;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiDetailSearchOption;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.baidu.mapapi.search.sug.OnGetSuggestionResultListener;
import com.baidu.mapapi.search.sug.SuggestionResult;
import com.baidu.mapapi.search.sug.SuggestionSearch;
import com.baidu.mapapi.search.sug.SuggestionSearchOption;
import com.baidu.trace.LBSTraceClient;
import com.baidu.trace.api.entity.EntityInfo;
import com.baidu.trace.api.entity.EntityListRequest;
import com.baidu.trace.api.entity.EntityListResponse;
import com.baidu.trace.api.entity.FilterCondition;
import com.baidu.trace.api.entity.LatestLocation;
import com.baidu.trace.api.entity.OnEntityListener;
import com.baidu.trace.api.track.HistoryTrackRequest;
import com.baidu.trace.api.track.HistoryTrackResponse;
import com.baidu.trace.api.track.OnTrackListener;
import com.baidu.trace.api.track.QueryCacheTrackResponse;
import com.baidu.trace.api.track.TrackPoint;
import com.baidu.trace.model.CoordType;
import com.baidu.trace.model.ProcessOption;
import com.baidu.trace.model.SortType;
import com.baidu.trace.model.TransportMode;
import java.util.ArrayList;
import java.util.List;

public class BaibuMapTrackActivity extends AppCompatActivity {
    MapView mapView;
    private MapUtil mapUtil;
    private Toolbar tb;

    private HistoryTrackRequest historyTrackRequest;
    // 轨迹服务客户端
    public LBSTraceClient client;
    private String entityName = "testuser";
    private int serviceId = 149746;
    private BaiduMap baiduMap;
    private LocationClient locationClient;

    /**
     * 轨迹排序规则
     */
    private SortType sortType = SortType.asc;

    /**
     * 轨迹点集合
     */
    private List<LatLng> trackPoints = new ArrayList<>();
    private PoiSearch poiSearch;

    private EditText city;
    private EditText street;
    private PoiCitySearchOption searchOption;
    private SuggestionSearch suggestionSearch;
    // 请求标识
    int tag = 1;
    //设置活跃时间
    long activeTime = System.currentTimeMillis() / 1000 - 5*60;
    // 过滤条件
    FilterCondition filterCondition = new FilterCondition();
    // 返回结果坐标类型
    CoordType coordTypeOutput = CoordType.bd09ll;
    // 分页索引
    int pageIndex = 1;
    // 分页大小
    int pageSize = 100;
    private ArrayList<String> arrayList;
    private EntityListRequest request;

    private static final int BAIDU_READ_PHONE_STATE =100;
    private BitmapDescriptor bitmap;
    private EditText phone;
    private BitmapDescriptor makerBitmap;
    private View userInfoView;
    private TextView userInfoPhone;
    private TextView userInfoTime;
    private Button userInfoQusery,cancel;
    private boolean isManager=false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SDKInitializer.initialize(getApplicationContext());//初始化 百度地图 要放在setContentView（）之前
        setContentView(R.layout.activity_baibu_map_track);
        mapView= (MapView) findViewById(R.id.baiduTrackView);
        city= (EditText) findViewById(R.id.city);
        street= (EditText) findViewById(R.id.street);
        tb= (Toolbar) findViewById(R.id.tb);
        setSupportActionBar(tb);
        suggestionSearch = SuggestionSearch.newInstance();
        suggestionSearch.setOnGetSuggestionResultListener(listener);
            initBaiduMap();
            initUI();

    }
    OnGetSuggestionResultListener listener = new OnGetSuggestionResultListener() {
        public void onGetSuggestionResult(SuggestionResult res) {
            List<SuggestionResult.SuggestionInfo> allSuggestions = res.getAllSuggestions();
            //Log.i("TRAIL","-----allSuggestions----"+allSuggestions.size());
            for (int i = 0; i < allSuggestions.size(); i++) {
                String district = allSuggestions.get(i).district;
                String uid = allSuggestions.get(i).uid;
                //allSuggestions.get(i).
                //Log.i("TRAIL","------district---"+district+"------uid---"+uid);
                //uid是POI检索中获取的POI ID信息
                poiSearch.searchPoiDetail((new PoiDetailSearchOption()).poiUid(uid));
            }

        }
    };

    @Override
    protected void onStart() {
        super.onStart();
        if(!isManager){
            Intent intent = getIntent();
            String[] arrays = intent.getStringArrayExtra("array");
            ShowUserLocation(arrays);
        }

    }

    private void ShowUserLocation(String[] arrays) {
        List<String> list=new ArrayList<>();
        for (int i = 0; i < arrays.length; i++) {
            list.add(arrays[0]);
        }
        if(list.size()>0){
            QueryAllEntityLocation(list);
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.baidumap_menu,menu);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.trajectory_query:
                QueryHistoryDialog();
                break;

            case R.id.location_query:
                QueryAllEntityLocation(null);
                break;
            case R.id.clean_map:
                baiduMap.clear();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void initUI() {
        client=new LBSTraceClient(getApplicationContext());
        mapUtil = MapUtil.getInstance();
        mapUtil.init(mapView);


        historyTrackRequest = new HistoryTrackRequest();
        // 开始时间(单位：秒)
        long startTime = System.currentTimeMillis() / 1000 - 12 * 60 * 60;;
        // 结束时间(单位：秒)
        long endTime = System.currentTimeMillis() / 1000;
        // 设置开始时间
        historyTrackRequest.setStartTime(startTime);
        // 设置结束时间
        historyTrackRequest.setEndTime(endTime);
        //historyTrackRequest.setEntityName(entityName);
        historyTrackRequest.setPageIndex(1);
        historyTrackRequest.setPageSize(5000);
        historyTrackRequest.setServiceId(serviceId);

        // 设置需要纠偏
        historyTrackRequest.setProcessed(true);
       // 创建纠偏选项实例
        ProcessOption processOption = new ProcessOption();
         // 设置需要去噪
        processOption.setNeedDenoise(true);
           // 设置需要抽稀
        processOption.setNeedVacuate(true);
         // 设置需要绑路
        processOption.setNeedMapMatch(true);
        // 设置精度过滤值(定位精度大于100米的过滤掉)
        processOption.setRadiusThreshold(100);
        // 设置交通方式为驾车
        processOption.setTransportMode(TransportMode.driving);
        historyTrackRequest.setProcessOption(processOption);

    }
    private BaiduMap.OnMarkerClickListener  markerClickListener=new BaiduMap.OnMarkerClickListener() {
        @Override
        public boolean onMarkerClick(Marker marker) {
            Bundle bundle = marker.getExtraInfo();
            if(bundle == null){return false;}
            final String name = bundle.getString("name");
            String createtime = bundle.getString("createtime");
            userInfoView=LayoutInflater.from(BaibuMapTrackActivity.this).inflate(R.layout.user_location_info,null);
            userInfoPhone= (TextView) userInfoView.findViewById(R.id.phone);
            userInfoTime= (TextView) userInfoView.findViewById(R.id.firstTime);
            userInfoQusery= (Button) userInfoView.findViewById(R.id.location_query);
            cancel= (Button) userInfoView.findViewById(R.id.cancel);
            userInfoPhone.setText(name);
            userInfoTime.setText(createtime);

            //Toast.makeText(BaibuMapTrackActivity.this," 点击了marker"+"--"+name+"--"+createtime,Toast.LENGTH_SHORT).show();
            AlertDialog.Builder builder = new AlertDialog.Builder(BaibuMapTrackActivity.this);
            final AlertDialog dialog = builder.setView(userInfoView).create();
            dialog.show();
            userInfoQusery.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    QueryHistory(name);
                    dialog.dismiss();
                }
            });
            cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });
            return false;
        }
    };

    private void initBaiduMap() {
        poiSearch = PoiSearch.newInstance();
        poiSearch.setOnGetPoiSearchResultListener(poiListener);
        baiduMap= mapView.getMap();
        baiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);//普通地图
        // baidumap.setMapType(BaiduMap.MAP_TYPE_SATELLITE);//卫星地图
        baiduMap.setMyLocationEnabled(true);
        locationClient = new LocationClient(getApplicationContext());
        locationClient.registerLocationListener(new MycityLocationListener());
        baiduMap.setOnMarkerClickListener( markerClickListener);
        setLocationOption();
    }
    private boolean isFirstLocate=true;
    private void MoveMyLocation(BDLocation bdLocation){
        if(isFirstLocate){
            LatLng latLng = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());
            MapStatusUpdate update = MapStatusUpdateFactory.newLatLng(latLng);
            baiduMap.animateMapStatus(update);
            //update = MapStatusUpdateFactory.zoomTo(16f);
            //baiduMap.animateMapStatus(update); //设置级别 在华为 6.0 以上有点问题 所以我把它屏蔽了
            isFirstLocate = false;
        }


        MyLocationData.Builder builder = new MyLocationData.Builder();
        builder.accuracy(bdLocation.getRadius());
        builder.latitude(bdLocation.getLatitude());
        builder.longitude(bdLocation.getLongitude());
        MyLocationData build = builder.build();
        baiduMap.setMyLocationData(build);





    }
    private void setLocationOption() {
        LocationClientOption locationClientOption = new LocationClientOption();
        locationClientOption.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);//设置高精度模式
        locationClientOption.setOpenGps(true);
        locationClientOption.setCoorType("bd0911");
        locationClientOption.setIsNeedAddress(true);//设置是否需要地址信息，默认不需要,不设置的话bdLocation 为null
        locationClientOption.setScanSpan(60*1000);//每隔60秒自动更新定位
        locationClientOption.setIsNeedLocationPoiList(true);

        locationClient.setLocOption(locationClientOption);
        locationClient.start();

    }
    private void QueryHistoryDialog(){
        View view = LayoutInflater.from(this).inflate(R.layout.baidu_map_dialog, null);
        phone = (EditText) view.findViewById(R.id.phone);
        new AlertDialog.Builder(this)
                .setTitle("输入查询手机号码")
                .setView(view)
                .setNegativeButton("取消",null)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String  userphone= phone.getText().toString();
                        QueryHistory(userphone);
                    }
                })
                .create()
                .show();
    }

    // 查询历史轨
    private void QueryHistory(String Userphone){
        historyTrackRequest.setEntityName(Userphone);
        client.queryHistoryTrack(historyTrackRequest,onTrackListener);

        //client.queryEntityList();

    }
    // 查询历史轨迹监听
    private OnTrackListener onTrackListener=new OnTrackListener() {
        @Override
        public void onHistoryTrackCallback(HistoryTrackResponse Response) {
            super.onHistoryTrackCallback(Response);
            String message = Response.getMessage();
            int status = Response.getStatus();
            int size = Response.getSize();
            List<TrackPoint> points = Response.getTrackPoints();
           // Log.i("location","---message--QueryCacheTrack---"+message+"---"+size+"----points--"+points.size());
            if(size == 0){
                Toast.makeText(BaibuMapTrackActivity.this,"没有获取到结果",Toast.LENGTH_SHORT).show();
            }
            if(status ==0){
                if (null != points) {
                    for (TrackPoint trackPoint : points) {
                        if (!MapUtils.isZeroPoint(trackPoint.getLocation().getLatitude(),
                                trackPoint.getLocation().getLongitude())) {
                            trackPoints.add(MapUtils.convertTrace2Map(trackPoint.getLocation()));
                        }
                    }
                    mapUtil.drawHistoryTrack(trackPoints, sortType);
                }
            }else {
                Toast.makeText(BaibuMapTrackActivity.this,"获取历史轨迹失败",Toast.LENGTH_SHORT).show();
            }



        }

        @Override
        public void onQueryCacheTrackCallback(QueryCacheTrackResponse queryCacheTrackResponse) {
            super.onQueryCacheTrackCallback(queryCacheTrackResponse);
            String message = queryCacheTrackResponse.getMessage();
            Log.i("TRAIL","---message--QueryCacheTrack---"+message);
        }
    };




    //查询所有单位
    private void QueryAllEntityLocation(List<String> list){
        // 查找当前时间5分钟之内有定位信息上传的entity
        filterCondition.setActiveTime(activeTime);
        if(!isManager){
            filterCondition.setEntityNames(list);
        }

        // 创建Entity列表请求实例
        if(request == null){
            request = new EntityListRequest(tag, Constant.SERVICE_ID, filterCondition, coordTypeOutput, pageIndex, pageSize);
        }
        // 查询Entity列表
        client.queryEntityList(request, entityListener);

    }

    // 查询实时位置 监听器 查询结果为百度地图的坐标
    private OnEntityListener entityListener = new OnEntityListener() {
        @Override
        public void onEntityListCallback(EntityListResponse entityListResponse) {
            super.onEntityListCallback(entityListResponse);
            String message = entityListResponse.getMessage();
            List<EntityInfo> entities = entityListResponse.getEntities();
            Log.i("location","---------"+entities.size());
            if(entities ==null || entities.size() ==0){
                if(entities.size() ==0){
                    Toast.makeText(BaibuMapTrackActivity.this,"没有在线设备",Toast.LENGTH_SHORT).show();
                }
                return;
            }
            //构建Marker图标
            if(makerBitmap ==null){
                makerBitmap= BitmapDescriptorFactory
                        .fromResource(R.mipmap.icon_markx);
            }
            OverlayOptions option;
            Bundle bundle;
            baiduMap.clear();//先清除以前的覆盖物
            for (int i = 0; i < entities.size(); i++) {
                EntityInfo entityInfo = entities.get(i);
                String mentityName = entityInfo.getEntityName();
                String createTime = entityInfo.getCreateTime();
                String entityDesc = entityInfo.getEntityDesc();
                LogUtil.i("locationinfo","-----mentityName---"+mentityName+"--createTime---"+createTime+"--entityDesc---"+entityDesc);

                com.baidu.trace.model.LatLng location = entityInfo.getLatestLocation().getLocation();
                LatLng latl = new LatLng(location.getLatitude(), location.getLongitude());

                //构建MarkerOption，用于在地图上添加Marker，地图上的自定义的标签和
                 bundle = new Bundle();
                bundle.putString("name",mentityName);
                bundle.putString("createtime",createTime);
                option = new MarkerOptions()
                        .position(latl)
                        .icon(makerBitmap)
                        .extraInfo(bundle);

                baiduMap.addOverlay(option);
            }
            //将第一个 设置为移动点
            com.baidu.trace.model.LatLng location = entities.get(0).getLatestLocation().getLocation();
            MapStatus mMapStatus = new MapStatus.Builder()
                    //要移动的点
                    .target(new LatLng(location.getLatitude(),location.getLongitude()))
                    //放大地图到16倍
                    .zoom(16)
                    .build();

            MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
            baiduMap.setMapStatus(mMapStatusUpdate);

           /* if(!CommonUtil.isZeroPoint(latitude,longitude)){
                LatLng latl = new LatLng(latitude, longitude);
                //在地图上添加Marker，并显示
                MapStatus mMapStatus = new MapStatus.Builder()
                        //要移动的点
                        .target(latl)
                        //放大地图到20倍
                        .zoom(16)
                        .build();

                MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
                baiduMap.setMapStatus(mMapStatusUpdate);


            }*/



        }
    };


   private OnGetPoiSearchResultListener poiListener = new OnGetPoiSearchResultListener(){
        public void onGetPoiResult(PoiResult result){
            //获取POI检索结果
            List<PoiInfo> allPoi = result.getAllPoi();

            if(allPoi == null|| allPoi.size() == 0){
                return;
            }
            Log.i("TRAIL","----allPoi长度-----"+allPoi.size());
            //LatLng location = allPoi.get(0).location;
            for (int i = 0; i <allPoi.size() ; i++) {
                String address = allPoi.get(i).address;
                String city = allPoi.get(i).city;
                String name = allPoi.get(i).name;
                Log.i("TRAIL","----详细地址---"+address+"---city--"+city+"----name---"+name);
            }


        }
        public void onGetPoiDetailResult(PoiDetailResult result){
            //获取Place详情页检索结果result
            String address = result.getAddress();
            Log.i("TRAIL","----结果--"+address);

        }

        @Override
        public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {

        }
    };

    public void getHistory(View view) {
        //QueryHistory();
    }




    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        locationClient.stop();
        mapView.onDestroy();
        baiduMap.setMyLocationEnabled(false);
        poiSearch.destroy();
    }

    public void Myselete(View view) {


        String mcity= city.getText().toString();
        String mstreet = street.getText().toString();
        searchOption = new PoiCitySearchOption();

        searchOption.city(mcity);
        searchOption.keyword(mstreet);
        searchOption.pageNum(10);
        searchOption.isReturnAddr(true);//
        poiSearch.searchInCity(searchOption);
        /*suggestionSearch.requestSuggestion((new SuggestionSearchOption())
                .keyword(mstreet)
                .city(mcity));*/

    }

    /**
     * 城市内搜索,直接根据输入框的内容去实现Poi搜索.
     */
    private void citySearch(int page) {
        // 设置检索参数
        PoiCitySearchOption citySearchOption = new PoiCitySearchOption();
        citySearchOption.city(city.getText().toString());// 城市
        citySearchOption.keyword(street.getText().toString());// 关键字
        citySearchOption.pageCapacity(15);// 默认每页10条
        citySearchOption.pageNum(page);// 分页编号
        // 为PoiSearch设置搜索方式.
        poiSearch.searchInCity(citySearchOption);
    }


    class MycityLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            //Log.i("TRAIL","----状态-----"+bdLocation.getLocType());
            MoveMyLocation(bdLocation);


            String str = bdLocation.getAddrStr();
            String city = bdLocation.getCity();
            Log.i("TRAIL","----当前位置-----"+str+"----当前城市-----"+city);
            // bdLocation.getProvince();//获取省份   还有其他获取城市、街道等
        }

    }
}
